<template>
	<div class="wrapper xinJian">
		<myhead :activeIndex="`/knowledgeList`"></myhead>
		<div class="content">
			<div class="content-item1">
				<div class="information f16">
					<h3>
						<el-icon style="margin-right: 5px"> <Connection /> </el-icon>基本信息
					</h3>
					<div class="information-text f14">{{ titileName }}</div>
				</div>
				<div>
					<el-form ref="formRef" :rules="rules" :model="form" label-width="140px">
						<div class="content-top">
							<div class="content-top-item span-2">
								<el-form-item label="标题" prop="title">
									<el-input
										placeholder="请输入标题"
										v-model="form.title"
										class="width-item"
										:maxlength="255"
										style="width: 100%"
									/>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="所属分类" prop="categoryId">
									<el-select
										class="width-item"
										style="width: 100%"
										v-model="form.categoryId"
										placeholder="请选择分类"
									>
										<el-option
											v-for="item in classification"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										>
										</el-option>
									</el-select>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="作者" prop="auth" ref="elFormItemAuthRef">
									<v-department
										v-model="form.auth"
										:placeholder="'请选择作者'"
										:title="'选择作者'"
										:placeholders="'请输入用户名进行搜索'"
										@close="onAuthClose"
									></v-department>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="发布部门" prop="deptId" ref="elFormItemAuthRefs">
									<v-bumen
										v-model="form.deptId"
										:placeholder="'请选择部门'"
										:title="'选择部门'"
										:placeholders="'请输入部门进行搜索'"
										@close="onDeptClose"
									></v-bumen>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="发布时间" prop="pubTime">
									<el-date-picker
										style="width: 100%"
										v-model="form.pubTime"
										type="date"
										placeholder="选择发布日期"
										value-format="YYYY-MM-DD 00:00:00"
										:disabled-date="disabledDates"
									>
									</el-date-picker>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="过期时间">
									<div class="width-item">
										<el-date-picker
											:disabled-date="disabledDate"
											style="width: 100%"
											v-model="form.expTime"
											type="date"
											placeholder="选择过期日期"
											value-format="YYYY-MM-DD 00:00:00"
										>
										</el-date-picker>
										<!-- <div style="font-size: 12px; color: #ccc" class="f12">
											为空表示永不过期，过期后将自动变为草稿（草稿仅自己可见）
										</div> -->
									</div>
								</el-form-item>
							</div>

							<div class="content-top-item no-inline">
								<el-form-item label="标签">
									<v-select-tags v-model="form.label" :mdKey="mdk5" :format="format">
										<template #tags="{ onOpenDialog, onDelete, selectedNames }">
											<div class="width-item-tags" style="width: 100%">
												<div v-if="selectedNames.length">
													<el-tag v-for="(item, index) in selectedNames" class="mx-1">
														{{ item }}
													</el-tag>
													<el-button
														type="primary"
														style="margin-left: 12px"
														@click="onOpenDialog"
														>编辑标签</el-button
													>
												</div>
												<el-input
													v-else
													style="width: 100%"
													type="text"
													placeholder="请选择标签"
													readonly
													@click="onOpenDialog"
												>
												</el-input>
											</div>
										</template>
									</v-select-tags>
								</el-form-item>
							</div>
							<div class="content-top-item no-inline">
								<el-form-item label="摘要" prop="remark">
									<el-input
										placeholder="请输入摘要"
										v-model="form.remark"
										class="width-item"
										type="textarea"
										maxlength="500"
										show-word-limit
										:autosize="{
											minRows: 5,
											maxRows: 10,
										}"
										style="width: 100%"
									/>
								</el-form-item>
							</div>
							<div class="content-top-item">
								<el-form-item label="附件上传" prop="attachments">
									<div style="width: 100%">
										<v-upload v-model="form.attachments" :type="'file'" :spacer="false" :max="1" />
									</div>
								</el-form-item>
							</div>
						</div>
					</el-form>
				</div>
			</div>
			<div class="content-item2">
				<div class="information">
					<h3>
						<el-icon style="margin-right: 5px" class="f18"> <Notification /> </el-icon>其他信息
					</h3>
				</div>
				<div class="form-div">
					<el-form ref="ruleFormRef" :model="tabalDate" label-width="140px">
						<div class="form-item">
							<el-form-item v-for="item in list" :key="item.id" class="form-el-item">
								<template #label>
									<span v-if="item.isRequired == 1" style="color: red; margin-right: 4px">*</span>
									<el-tooltip
										class="box-item"
										effect="light"
										:content="item.name"
										placement="top-start"
										:offset="0"
									>
										<div class="nameLabel">{{ item.name }}</div>
									</el-tooltip>
								</template>
								<el-input
									class="width-item-t"
									v-model="tabalDate[item.propName]"
									type="text"
									v-if="item.formType == 1"
									:maxlength="200"
									show-word-limit
								></el-input>
								<el-input
									v-else-if="item.formType == 2"
									v-model="tabalDate[item.propName]"
									type="textarea"
									class="width-item-t maxTextarea"
									:autosize="{
										minRows: 2,
										maxRows: 4,
									}"
									:maxlength="1000"
									show-word-limit
								></el-input>
								<div v-else-if="item.formType == 3" class="width-item-t">
									<el-date-picker
										v-model="tabalDate[item.propName]"
										type="date"
										style="width: 100%"
										placeholder="选择日期时间"
										value-format="YYYY-MM-DD 00:00:00"
									>
									</el-date-picker>
								</div>
								<v-upload
									:type="'file'"
									v-else-if="item.formType == 4"
									v-model="tabalDate[item.propName]"
									:spacer="false"
									:max="1"
								/>
								<div class="width-item-t">
									<el-select v-model="tabalDate[item.propName]" v-if="item.formType == 5" clearable>
										<el-option
											v-for="item in JSON.parse(item.selectFrame)"
											:key="item.name"
											:label="item.name"
											:value="item.name"
										/>
									</el-select>
								</div>
							</el-form-item>
							<div class="form-bottom">
								<el-button @click="router.go(-1)">取消</el-button>
								<el-button v-loading="loading" type="warning" @click="submit('draft')"
									>保存草稿</el-button
								>
								<el-button v-loading="loadings" type="primary" @click="submit('sub')">提交</el-button>
							</div>
						</div>
					</el-form>
				</div>
			</div>
			<el-dialog v-model="dialogVisible" title="提示" class="dialog" :before-close="handleClose">
				<div class="dialogVisible">
					<div class="dialogVisible-img">
						<img src="@/assets/image/zhuTi/chengGong.png" alt="" />
					</div>
					<div>
						<div class="dialogVisible-title">操作成功</div>
						<div>
							{{ dialogTime }}秒后页面自动关闭
							<span style="color: #2971ff; cursor: pointer; padding-left: 10px" @click="handleClose"
								>立即跳转</span
							>
						</div>
					</div>
				</div>
			</el-dialog>
		</div>
		<v-myfoot></v-myfoot>
	</div>
</template>

<script setup>
import { useDictStore } from "/store/dict"
import { getAxios, postAxios } from "/axios"
import vSelectTags from "/packages/v-select-tags/index.vue"
import { Notification } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"

const form = reactive({
	title: "", //标题
	auth: [], //作者
	deptId: [], //部门
	pubTime: "", //发布时间
	expTime: "", //过期时间
	labels: [], //标签
	remark: "", //标签
	attachments: [], //附件
	categoryId: "", //分类
	modelId: "",
})
const dialogVisible = ref(false)
const dialogTime = ref(3)
const router = useRouter()
const list = ref([])
const dictSrc = ref([])
const route = useRoute()
let tabalDate = ref({})
const formRef = ref()
//效验
const rules = reactive({
	title: [{ required: true, message: "请输入标题", trigger: "blur" }],
	auth: [{ required: true, message: "请选择作者", trigger: "change" }],
	deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
	pubTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
	attachments: [{ required: true, message: "最少上传一个附件", trigger: "blur" }],
	categoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
	remark: [{ required: true, message: "请输入摘要", trigger: "blur" }],
})
const mdk5 = computed(() => {
	let fileList = [...form.attachments]
	list.value.forEach(item => {
		if (item.formType == 4) {
			fileList = fileList.concat(tabalDate.value[item.propName])
		}
	})
	return fileList.map(item => item && item.md5).filter(item => item) || []
})

const title = ref("")
const titileName = ref("")
const set = ref(null)
const classification = ref([])
const tagList = ref([])
const elFormItemAuthRef = ref()
const elFormItemAuthRefs = ref()
const loading = ref(false)
const loadings = ref(false)
const fabu = ref(false)

async function cread() {
	//所有分类
	const resAdd = await getAxios(`/knowledge/kbCategory/findBySwWidToBackstageAdd?swId=${route.query.swId}`)
	classification.value = resAdd
	//用户标签
	tagList.value = await getAxios(`/knowledge/kbBasicLabel/list?bId=${route.query.id}`)
	//1 获取用户数据
	const res = await getAxios(`/kb/kbBasic/findBasic?id=${route.query.id}`)
	//2 动态列表
	list.value = await getAxios(`/kb/kbColConfig/list?status=1&swId=${route.query.swId}`)
	title.value = res.swName
	form.title = res.title
	form.auth[0] = {
		realName: res.createName,
		id: res.createUserId,
	}
	form.deptId[0] = {
		name: res.deptName,
		id: res.deptId,
	}
	form.pubTime = res.pubTime
	form.expTime = res.expTime
	form.remark = res.remark
	form.labels = tagList.value.filter(item => item) || []
	form.attachments = res.attachments
	form.categoryId = res.ctId
	tabalDate.value = res.cols
}
//枚举
async function dict() {
	dictSrc.value = await useDictStore().getDict("/system/enums/list?enumName=FromType&moduleName=knowledge")
}
dict()

cread()

function onAuthClose() {
	elFormItemAuthRef.value.clearValidate()
}
function onDeptClose() {
	elFormItemAuthRefs.value.clearValidate()
}
function disabledDates(time) {
	return time.getTime() < Date.now() - 8.64e7
}
const submit = async item => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		try {
			try {
				await formRef.value.validate()
			} catch (error) {
				return
			}
			let flag = false
			let col = ref("")
			list.value.map(item => {
				if (item.isRequired == 1) {
					if (!tabalDate.value[item.propName]) {
						flag = true
						col = item.name
					}
				}
			})

			if (flag) {
				// todo message
				return ElMessage.error(`请输入${col}`)
				fabu.value = false
			}
			let src = {}
			src.title = form.title
			src.id = route.query.id
			src.auth = form.auth[0].id
			src.deptId = form.deptId[0].id
			src.pubTime = form.pubTime
			src.expTime = form.expTime
			src.labels = form.labels
			let listAtt = ""
			src.attachments = form.attachments
			src.remark = form.remark
			src.categoryId = form.categoryId
			src.modelId = list.value[0].modelId
			let listLabel = []
			form.labels.forEach(item => {
				listLabel.push({
					name: item.name,
					status: item.status,
				})
			})
			src.labels = listLabel
			let tabalDateList = {}
			src.cols = tabalDateList
			src.cols = tabalDate.value
			if (item == "sub") {
				//修改
				try {
					src.status = 1
					await postAxios("/kb/modelBaisc/updataData", src)
					cread()
					dialogVisible.value = true
					set.value = setInterval(() => {
						dialogTime.value = dialogTime.value - 1
						if (dialogTime.value == 0) {
							ElMessage.success("修改成功")
							router.back()
							clearInterval(set.value)
						}
					}, 1000)
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				//保存草稿
				try {
					src.status = 2
					await postAxios("/kb/modelBaisc/updataData", src)
					cread()
					dialogVisible.value = true
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			}

			// clean()
		} catch (error) {
			ElMessage.error(error)
			fabu.value = false
		}
	}
}
function addZero(s) {
	return s < 10 ? "0" + s : s
}
const disabledDate = time => {
	let timeS = new Date(form.pubTime).getTime()
	return time.getTime() < new Date(form.pubTime).getTime()
}
const quxiao = () => {
	router.push(`/knowledgeDetails?id=${route.query.id}&swId=${route.query.swId}`)
}
const handleClose = () => {
	clearInterval(set.value)
	ElMessage.success("修改成功")
	router.back()
}
</script>
<style lang="scss" scoped>
@import "/style/basis";

.xinJian {
	background-color: #f8f8f8;

	.content {
		width: 100%;
		padding: 25px 50px;
		background-color: #f8f8f8;
		border-radius: 10px;

		@include maxWidth(1024) {
			display: block;
		}

		@include maxWidth(575) {
			padding: 2vw;
		}

		.content-item1 {
			background-color: #fff;
			margin-bottom: 10px;
			border-radius: 10px;
			width: 100%;
			padding: 40px;
			overflow: hidden;

			.content-top {
				display: flex;
				flex-wrap: wrap;

				.content-top-item {
					width: 33.33%;

					@include maxWidth(1350) {
						width: 50%;
					}

					@include maxWidth(980) {
						width: 100%;
					}
					&.span-2 {
						width: 66.6666%;
					}
					&.no-inline {
						width: 100%;
					}
				}
			}

			@include maxWidth(1024) {
				width: 100%;
				border: 0;
			}

			@include maxWidth(555) {
				padding: 0 5vw;
			}

			.information {
				margin: 15px 0;
			}

			.information-content {
				display: flex;

				@include maxWidth(1024) {
					margin-left: 0;
				}
			}

			.information-text {
				padding-left: 20px;
			}
		}

		.content-item1::-webkit-scrollbar {
			overflow: -moz-hidden-unscrollable;
		}

		.content-item2 {
			width: 100%;
			border-radius: 10px;
			background-color: #fff;
			padding: 40px;
			position: relative;

			.form-div {
				width: 100%;
				display: flex;
				flex-wrap: wrap;
				margin-bottom: 50px;
				:deep(form) {
					width: 100%;
				}

				.form-item {
					width: 100%;
					display: flex;
					flex-wrap: wrap;
					padding-bottom: 80px;

					.form-el-item {
						width: 33%;

						@include maxWidth(1350) {
							width: 50%;
						}

						@include maxWidth(980) {
							width: 100%;
						}
					}
				}
			}

			:deep(.el-form-item__content) {
				display: block;
			}

			.form-bottom {
				position: absolute;
				width: 100%;
				bottom: 20px;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			@include maxWidth(1024) {
				width: 100%;
				border: 0;
			}

			@include maxWidth(555) {
				padding: 0 5vw;
			}

			.information {
				margin: 10px 0;
			}

			.nameLabel {
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}

		.content-disNo {
			display: block;

			@include maxWidth(1024) {
				display: none;
			}
		}

		.content-disNo-2 {
			display: none;

			@include maxWidth(1024) {
				display: block;

				border-top: 1px solid #f1f1f1;
			}
		}

		.content-item2::-webkit-scrollbar {
			overflow: -moz-hidden-unscrollable;
		}
	}
}

.width-item {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

.width-item-t {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

.width-item-label {
	width: 450px;

	.mx-1 {
		margin-right: 10px;
	}
}

.maxTextarea {
	max-height: 250px;
}

.dialogVisible {
	display: flex;
	padding-left: 50px;

	.dialogVisible-img {
		width: 80px;
		height: 80px;
		margin-right: 30px;

		img {
			width: 100%;
			height: 100%;
		}
	}

	.dialogVisible-title {
		font-size: 20px;
		color: #1296db;
		padding-bottom: 20px;
	}
}

:deep(.dialog) {
	width: 500px !important;
}
</style>
